package com.jdk7.mo.config;

import com.jdk7.mo.entity.Student;
import com.jdk7.mo.listener.BaseJobListener;
import com.jdk7.mo.process.StudentItemProcessor;
import com.jdk7.mo.reader.StudentFieldSetMapper;
import com.jdk7.mo.writer.StudentItemWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

@Configuration
public class StudentJobConfig {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    // begin reader, writer, and processor
    @Bean
    public FlatFileItemReader<Student> csvStudentReader() {
        FlatFileItemReader<Student> reader = new FlatFileItemReader<Student>();
        reader.setResource(new ClassPathResource("csv/student.csv"));
        reader.setLinesToSkip(1);
        reader.setLineMapper(new DefaultLineMapper<Student>() {{
            setLineTokenizer(new DelimitedLineTokenizer() {{
                setNames(new String[]{"id", "name", "sex", "birthDate", "homeAddress", "school", "grade"});
            }});
            setFieldSetMapper(new StudentFieldSetMapper());
        }});
        return reader;
    }


    @Bean
    ItemProcessor<Student, Student> csvStudentProcessor() {
        return new StudentItemProcessor();
    }

    @Bean
    public ItemWriter<Student> csvStudentWriter() {
        StudentItemWriter writer = new StudentItemWriter();
        return writer;
    }
    // end reader, writer, and processor

    // begin job info
    @Bean
    public Step csvStudentToDBStep() {
        return stepBuilderFactory.get("csvStudentToDBStep")
                .<Student, Student>chunk(10)
                .reader(csvStudentReader())
                .processor(csvStudentProcessor())
                .writer(csvStudentWriter())
                .build();
    }

    @Bean
    Job studentJob(BaseJobListener listener) {
        return jobBuilderFactory.get("studentJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener)
                .flow(csvStudentToDBStep())
                .end()
                .build();
    }
    // end job info
}
